package com.gofaraway.service.student.leetCodeV2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ChenPeng
 * @date 2025/5/8 19:25
 */
public class 三数之和 {

    public static List<List<Integer>> threeSum(int[] nums) {
        //先排序
        Arrays.sort(nums);

        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            //跳过重复元素
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int L = i + 1;
            int R = nums.length - 1;

            int target = -nums[i];

            while (L < R) {
                int res = nums[L] + nums[R];
                if (res == target) {
                    result.add(Arrays.asList(nums[i], nums[L], nums[R]));
                    L++;
                    R--;
                    //跳过重复元素
                    while (L < R && nums[L] == nums[L - 1]) {
                        L++;
                    }
                    while (L < R && nums[R] == nums[R + 1]) {
                        R--;
                    }
                } else if (res < target) {
                    L++;
                } else {
                    R--;
                }
            }
        }

        return result;
    }
}
